package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.mapper.TransFlowMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.bo.TransFlowBO;
import com.atguigu.srb.core.pojo.entity.TransFlow;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.service.TransFlowService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 交易流水表 服务实现类
 * </p>
 *
 * @author javaCode
 * @since 2025-07-19
 */
@RequiredArgsConstructor
@Service
public class TransFlowServiceImpl extends ServiceImpl<TransFlowMapper, TransFlow> implements TransFlowService {

    // 用户基本信息 Mapper 接口
    private final UserInfoMapper userInfoMapper;

    /**
     * 保存交易流水
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveTransFlow(TransFlowBO transFlowBO) {
        // 获取用户基本信息 user_info
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getBindCode, transFlowBO.getBindCode());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);

        // 存储交易流水数据
        TransFlow transFlow = new TransFlow();

        transFlow.setUserId(userInfo.getId());
        transFlow.setUserName(userInfo.getName());
        transFlow.setTransNo(transFlowBO.getAgentBillNo());
        transFlow.setTransType(transFlowBO.getTransTypeEnum().getTransType());
        transFlow.setTransTypeName(transFlowBO.getTransTypeEnum().getTransTypeName());
        transFlow.setTransAmount(transFlowBO.getAmount());
        transFlow.setMemo(transFlowBO.getMemo());

        baseMapper.insert(transFlow);
    }

    /**
     * 判断流水是否存在
     */
    @Override
    public boolean isSaveTransFlow(String agentBillNo) {
        LambdaQueryWrapper<TransFlow> wrapper = new LambdaQueryWrapper<TransFlow>().eq(TransFlow::getTransNo, agentBillNo);
        Integer count = baseMapper.selectCount(wrapper);

        return count > 0;
    }

    /**
     * 获取列表
     */
    @Override
    public List<TransFlow> selectByUserId(Long userId) {
        LambdaQueryWrapper<TransFlow> wrapper = new LambdaQueryWrapper<TransFlow>().eq(TransFlow::getUserId, userId).orderByDesc(TransFlow::getId);
        return baseMapper.selectList(wrapper);
    }
}
